﻿package idv.cjcat.emitter.behaviors {
	use namespace engine;
	
	import idv.cjcat.emitter.*;
	
	/**
	 * Behavior trigger triggered by particle position. The test region is circle-shaped.
	 */
	public class CircleTrigger extends BehaviorTrigger {
		
		public var x:Number;
		public var y:Number;
		public var radius:Number;
		/**
		 * Whether the behavior trigger is triggered when a particle enters or leaves the circle-shaped region.
		 */
		public var triggerOnEnter:Boolean;
		
		public function CircleTrigger(x:Number = 0, y:Number = 0, radius:Number = 100, triggerOnEnter:Boolean = false) {
			this.x = x;
			this.y = y;
			this.radius = radius;
			this.triggerOnEnter = triggerOnEnter;
		}
		
		override public function test(pd:ParticleData):Boolean{
			var dx:Number = pd.cx - x;
			var dy:Number = pd.cy - y;
			if (triggerOnEnter) {
				if (dx * dx + dy * dy <= radius * radius) return true;
			} else {
				if (dx * dx + dy * dy > radius * radius) return true;
			}
			return false;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = BehaviorTriggerType.CIRCLE;
			xml.@x = x.toString();
			xml.@y = y.toString();
			xml.@radius = radius.toString();
			xml.@triggerOnEnter = triggerOnEnter.toString();
			
			return xml;
		}
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			
			x = parseFloat(xml.@x);
			y = parseFloat(xml.@y);
			radius = parseFloat(xml.@radius);
			triggerOnEnter = (xml.@triggerOnEnter == "true");
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}